from flask import request, jsonify, Blueprint
from flask_jwt import jwt_required, current_identity
from com.util import Rep
from com import db

# 注册蓝图
collect = Blueprint('collect', __name__)

# 添加收藏
@collect.route('/toAddMyCollect', methods=['POST'])
@jwt_required()
def toAddMyCollect():
    userInfo = current_identity
    body = request.json
    imageUrl = body.get('imageUrl', "")
    title = body.get('title', "")
    if imageUrl is None or imageUrl == '':
        return jsonify(Rep.Error(msg='请传入商品图片'))
    con = db.get_db()
    con.execute("insert into user_collect (u_id, pic_url, title) values (?, ?, ?) ", [userInfo.id, imageUrl, title])
    con.commit()

    return jsonify(Rep.Ok(msg='添加成功'))


# 移除我的收藏
@collect.route('/toRemoveMyCollect', methods=['DELETE'])
@jwt_required()
def toRemoveMyCollect():
    userInfo = current_identity
    body = request.args.to_dict()
    id = body.get('id')
    if id is None:
        return jsonify(Rep.Error("请输入id"))

    con = db.get_db_dict()
    oneCollect = con.execute("select * from user_collect where id = ?", [id]).fetchone()
    if oneCollect is None or oneCollect.get('u_id') != int(userInfo.id):
        return Rep.Error(msg='收藏信息错误')

    con.execute("delete from user_collect where id = ?", [id])
    con.commit()
    return Rep.Ok(msg='删除成功')


# 得到我的收藏
@collect.route('/myCollectList')
@jwt_required()
def myCollectList():
    userInfo = current_identity
    print("这是userInfo", userInfo)
    # body = request.args.__dict__
    # pageNum = int(body.get('pageNum', default=1))
    # pageSize = int(body.get('pageSize', default=10))
    # con = db.get_db_dict()
    # result = con.execute("select * from user_collect limit ?,?", [(pageNum - 1) * pageSize, pageSize]).fetchmany()

    con = db.get_db_dict()
    result = con.execute("select *  from user_collect where u_id = ? order by id desc", [userInfo.id]).fetchall()
    return Rep.Ok(data=result)